package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.constant.YanwuPayParam;
import cn.chinaflame.pagodas.entity.PaOrder;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.PaOrderRepository;
import cn.chinaflame.pagodas.req.PaydataReq;
import cn.chinaflame.pagodas.utils.*;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.SpringProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wwt
 * @date 2018年1月15日 下午8:00:41
 */
@Service
public class PayService {
    private final static Logger log = LoggerFactory.getLogger(PayService.class);

    @Autowired
    private PaOrderRepository paOrderRepository;

    
    
    /**
     * H5支付
     * @param req
     * @return
     */
    public String unifiedOrder(@RequestBody PaydataReq req) {

        PaOrder order = paOrderRepository.findOne(req.getOrderNo());
        ParamPreconditions.checkNotNull(order, CodeEnum.FAIL.getCode(), "未找到订单信息");
        paOrderRepository.saveAndFlush(order);
        req.setInputCharset(YanwuPayParam.inputCharset);
        req.setVersion(YanwuPayParam.version);
        req.setLanguage(YanwuPayParam.language);
        req.setOrderCurrency(YanwuPayParam.orderCurrency);
        req.setTradeType(YanwuPayParam.tradeType);
        req.setPayWay(YanwuPayParam.payWay);
        req.setNotifyUrl(SpringProperties.getProperty("pay.payment.notify_ty_url"));
        req.setOrderDatetime(DateTimes.nowDateTimetrim());
        req.setMerchantId(SpringProperties.getProperty("pay.payment.merchantId"));
        String url = SpringProperties.getProperty("pay.payment.url");
        String registKey = SpringProperties.getProperty("pay.payment.registKey");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("inputCharset", req.getInputCharset());
        params.put("returnUrl", req.getReturnUrl());
        params.put("notifyUrl", req.getNotifyUrl());
        params.put("version", req.getVersion());
        params.put("language", req.getLanguage());
        params.put("orderNo", req.getOrderNo());
        params.put("orderCurrency", req.getOrderCurrency());
        params.put("orderDatetime", req.getOrderDatetime());
        params.put("payType", req.getPayType());
        params.put("issuerId", req.getIssuerId());
        params.put("sign", req.getSign());
//		params.put("orderAmount", Long.valueOf(req.getOrderAmount()));
        params.put("orderAmount", req.getOrderAmount());
        params.put("merchantId", req.getMerchantId());
        params.put("tradeType", req.getTradeType());
        params.put("payWay", req.getPayWay());
        params.put("tradeChannel", req.getTradeChannel());
        params.put("tradeMethod", req.getTradeMethod());
        params.put("userId", req.getUserId());
        //判断是否在支付平台注册
        log.info("注册请求串userid:{},merchantId:{},registKey:{}", req.getUserId(), req.getMerchantId(), registKey);
        String rs = registered(req.getUserId(), req.getMerchantId(), registKey);
        log.info("注册结果rs:{}", rs);
        Map<String, String> val = Jackson.readJson(rs, new TypeRef<Map<String, String>>());
        if (!Sysconst.PAY_HAS_REGIST_CODE.equals(val.get("errorCode")))
            ParamPreconditions.checkArgument(Sysconst.PAY_SUCCESS_CODE.equals(val.get("errorCode")), CodeEnum.FAIL.getCode(),
                    "支付用户绑定失败");
        String reqEntity = Jackson.writeJson(params);
        log.info("支付请求串reqEntity:{}", reqEntity);
        String receive = HttpPostUtil.doPost(url, reqEntity);
        /**
         * pay.payment.url=http://tupay.china-flame.cn/gateway/trade/pay
         */

        //----------------------------------------------------------------------------------强哥---------------------------------------------
        Map<String, String> receiveMap = Jackson.readJson(receive, new TypeRef<Map<String, String>>());
        log.info("下单支付结果receive:{}", receive);
        if (Sysconst.PAY_SUCCESS_CODE.equals(receiveMap.get("errorCode"))) {
            order.setPayTime(DateTimes.nowDateTime());
            order.setUpdatetime(DateTimes.nowDateTime());
            order.setPayStatus(Sysconst.PAY_STATUS_DOING);
            order.setSerialNumber(receiveMap.get("orderNo"));
            order = paOrderRepository.saveAndFlush(order);
			/*ScheduleTime time = new ScheduleTime(15, TimeUnit.MINUTES);
			PaOrderFailure orderFailure = new PaOrderFailure(order.getId(), Sysconst.PAY_STATUS_DOING, Sysconst.PAY_STATUS_ORDER_TIMEOUT);
			PaOrderSchedule.getInstance().startTask(orderFailure, time);*/
        }
//		log.info("支付结果map:{}", receiveMap);
//		ParamPreconditions.checkArgument(Sysconst.PAY_SUCCESS_CODE.equals(receiveMap.get("errorCode")), CodeEnum.FAIL.getCode(), 
//				"下单支付失败");
		/*System.out.println("receive:"+receive);
		Map<String, String> val = Jackson.readJson(receive, new TypeRef<Map<String, String>>());
		if("200".equals(String.valueOf(val.get("code")))){
			Map<String, String> val2 = Jackson.readJson(String.valueOf(val.get("data")), new TypeRef<Map<String, String>>());
			if("JSAPI".equals(val2.get("paymethod"))){
				JSAPIPayRequest request = new JSAPIPayRequest();
				request.setAppid(val2.get("appId"));
				request.setTimestamp(val2.get("timeStamp"));
				request.setPkg(val2.get("package"));
				request.setSign(val2.get("paySign"));
				request.setSignType(val2.get("signType"));
				request.setNonceStr(val2.get("nonceStr"));
				request.setPayoid(val2.get("payoid"));
				return Result.create(request);
			}else if("SC_WX".equals(val2.get("paymethod")) || "SC_ZFB".equals(val2.get("paymethod"))){
				return Result.create(val2);
			}else if("YLTLH5".equals(val2.get("paymethod"))) {
				return Result.create(val2);
			}				
		}else{
			return Result.create("FAIL", val.get("msg"));
		}*/
        return receive;
    }

    public String registered(String userid, String merchantId, String key) {
        String url = "http://tupay.china-flame.cn/gateway/user/regist ";
        String queryStr = "merchantId=" + merchantId + "&partnerUserId=" + userid + "&key=" + key;
        System.out.println(Digests.md5DigestAsHex(queryStr));
        Map<String, String> map = Maps.newHashMap();
        map.put("merchantId", merchantId);
        map.put("partnerUserId", userid);
        map.put("sign", Digests.md5DigestAsHex(queryStr).toUpperCase());
        String receive = HttpPostUtil.doPost(url, Jackson.writeJson(map));
        return receive;
    }

    /**
     * H5退款
     *
     * @param req
     * @return
     */
    public String refund(String serialno, String amount) {
        String url = SpringProperties.getProperty("refund.payment.url");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("merchantId", SpringProperties.getProperty("pay.payment.merchantId"));
        params.put("orderAmount", amount);
        params.put("serialno", serialno);
        String reqEntity = Jackson.writeJson(params);
        System.out.println("退款参数：" + reqEntity);
        String receive = HttpPostUtil.doPost(url, reqEntity);
        return receive;
    }
    
    
    
    
    
    
    
    
    
    
}
